<template>
    <Dialog :app-dialog="appDialog" @close="closeDialog">
        <div v-show="props.tips" class="tips">注：仅支持同步客易达电商、有赞店铺在指定时间段内的用户数据</div>
        <!-- 搜索 -->
        <ZWSearch row-num="2" :option="searchOption" @search="search" @reset="reset" />
        <!-- 查询结果 -->
        <ZWTable
            ref="TableRef"
            class="table-box"
            tab-h="400px"
            :multiple="appDialog.multiple"
            :option="tableOption"
            :selected-ids="selectedIds"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            :row-key="getRowKey"
            @select="onSelect"
            @select-all="onSelectAll" />
    </Dialog>
</template>
<!-- 选择店铺 -->
<!-- 选择店铺 -->
<!-- 选择店铺 -->
<script setup lang="tsx">
import { reactive, ref, onMounted, computed, watch, watchEffect } from 'vue';
import { ElMessage } from 'element-plus';
import Dialog from '@/components/Dialog.vue';
import { getStoreList, getStoreSourceList } from '@/api/ecommerce/storeManage';
import ZWSearch from '@/components/zw/search-form/SearchForm';
import ZWTable from '@/components/zw/table/Table';
import { deepCopy } from '@/utils/helper';
import { SyncLine } from '@/const/ecommerce';

const TableRef = ref<HTMLElement | null>();
const selectedArr = reactive<any>([]);

interface Props {
    modelValue: boolean;
    show: boolean;
    multiple: boolean;
    tips: boolean;
    selectedMember: Array<unknown>;
    isDisabled: boolean;
}

const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    show: false,
    multiple: true,
    tips: false,
    selectedMember: () => [],
    // 是否根据条件禁用选择
    isDisabled: false
});
const emit = defineEmits(['update:modelValue', 'update:show', 'submit']);

const defaultParams = {
    page: 1,
    page_size: 15
};

const selectedIds = computed(() => props.selectedMember.map((item: any) => item.id));

const getRowKey = (row: any) => {
    return row.id;
};
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    return [
        {
            label: '店铺信息',
            name: 'shop_info',
            value: '',
            type: 'input',
            placeholder: '请输入店铺ID｜名称搜索'
        },
        {
            label: '店铺类型',
            name: 'source',
            value: '',
            type: 'select',
            placeholder: '请选择店铺类型',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getStoreSourceList({}).then((res: any) => {
                        const levelid: any = [];
                        res.forEach((item: any) => {
                            levelid.push(item);
                            resolve(levelid);
                        });
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建时间',
            name: 'created_at',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        }
    ];
});

/**
 * 不可选择客易达SCRM的店铺
 */
const selectEnable = (row: any, rowIndex: any) => {
    if (row.sync_line == SyncLine['RPA_SYNC_LINE'] && props.isDisabled) {
        return false;
    } else {
        return true;
    }
};

const tableOption = [
    {
        type: 'selection',
        width: 60,
        fixed: 'left',
        reserveSelection: true,
        selectable: selectEnable
    },
    {
        label: '店铺信息',
        width: 320,
        render({ row }: any) {
            return (
                <div class="store_msg">
                    <div class="avator">
                        <img v-show={row?.logo} class="store_avator" src={row?.logo} />
                        <img v-show={!row?.logo} class="store_avator" src={'/static/ecommerce/store_default.png'} />
                    </div>
                    <div class="content">
                        <div class="store_name">店铺ID {row?.id} </div>
                        <div class="store_tel"> {row?.name} </div>
                    </div>
                </div>
            );
        }
    },
    {
        prop: 'state',
        label: '店铺状态',
        width: 120,
        render({ row }: any) {
            return row.state == 1 ? '正常' : '异常';
        }
    },
    {
        prop: 'source_name',
        label: '店铺类型',
        width: 140
    },
    {
        prop: 'created_at',
        label: '创建时间'
    }
];
const search = (data: any): void => {
    state.searchParams = data;
    selectedArr.splice(0);
    TableRef.value.clearSelection();
};
const reset = (v: any): void => {
    state.searchParams = deepCopy(defaultParams);
    selectedArr.splice(0);
    TableRef.value.clearSelection();
};
const closeDialog = () => {
    state.searchParams = deepCopy(defaultParams);
};

const fetchApi = (): any => {
    return getStoreList;
};
// 选中表格 checkbox
const onSelect = (selection: any, row: any): void => {
    if (appDialog.multiple) {
        selectedArr.splice(0);
        selectedArr.push(...selection);
    } else {
        // TableRef.value.reload()
        selectedArr.splice(0);
        selectedArr.push(row);
    }
};

const onSelectAll = (selection: any): void => {
    selectedArr.splice(0);
    selectedArr.push(...selection);
};

// 取消
const cancelHandel = (): void => {
    appDialog.visible = false;
};
//确定
const submitHandel = (): void => {
    emit('submit', selectedArr);
    cancelHandel();
};
const appDialog = reactive({
    visible: false,
    title: '选择店铺',
    width: '900px',
    multiple: false,
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存'
});

watch(
    () => appDialog.visible,
    (val: boolean) => {
        emit('update:show', val);
    },
    { deep: true, immediate: true }
);
watch(
    () => props.show,
    (val: boolean) => {
        appDialog.visible = val;
    },
    { deep: true, immediate: true }
);

defineExpose({
    appDialog
});
</script>

<style lang="scss" scoped>
:deep .table_header_title {
    height: 60px;

    th.el-table__cell {
        background: #f9f9f9;
        padding: 10px 0;
    }
}

:deep .el-table__row {
    .el-table__cell {
        .store_msg {
            display: flex;
            align-items: center;

            .avator {
                width: 48px;
                height: 48px;
                border-radius: 50%;
                overflow: hidden;
                background-color: #eee;
                margin-right: 6px;

                .store_avator {
                    width: 100%;
                    height: 100%;
                }
            }

            .content {
                & > div {
                    font-size: 12px;
                    line-height: 1;
                }

                .store_name {
                    margin-bottom: 10px;
                }
            }
        }
    }
}

.tips {
    color: #ff6b00;
    background-color: #fffaf9;
    font-size: 14px;
    padding: 3px 10px;
}

.table-box {
    // height: 500px;
    // overflow: auto;
}
</style>
